# -*- coding: utf-8 -*-

import pymysql
from WebSite.Exceptions.myException import MyError


class MysqlTool(object):
    def __init__(self, **kwargs):
        if kwargs.get('user') is None or kwargs.get('password') is None or kwargs.get('host') is None:
            raise MyError('错误的参数', kwargs)
        try:
            self.cnx = pymysql.connect(**kwargs)
            self.cursor = self.cnx.cursor()
        except Exception as e:
            print(e)
            self.cnx.close()

    def do_select(self, sql, param=None):
        my_list = []
        if isinstance(param, tuple):
            self.cursor.execute(sql, param)
        elif param is None:
            self.cursor.execute(sql)
        else:
            raise MyError('参数错误', param)

        for i in self.cursor:
            my_list.append(i)
        return my_list

    def do_update(self, sql, param):
        if isinstance(param, tuple):
            self.cursor.execute(sql, param)
        elif param is None:
            self.cursor.execute(sql)
        else:
            raise MyError('参数错误', param)
        self.cnx.commit()

    def do_insert(self, sql, param):
        return self.do_update(sql, param)
